class Snake {
  element: HTMLElement;
  head: HTMLElement;
  // 蛇的身体
  bodyies: HTMLCollection;
  //蛇运动的方向,  #表示该属性为私有属性
  #direction: string = 'ArrowRight';
  constructor() {
    this.element = document.getElementById('snake')!;
    // 断言
    this.head = document.querySelector('#snake > .snake-body') as HTMLElement;
    this.bodyies = this.element.getElementsByClassName(
      'snake-body'
    ) as HTMLCollection;
  }

  // 获取到蛇头的 X轴坐标的方法
  get X() {
    return this.head.offsetLeft;
  }

  // 获取到蛇头的 Y轴坐标的方法
  get Y() {
    return this.head.offsetTop;
  }

  // 设置到蛇头的 X轴坐标的方法
  set X(offset: number) {
    // if (this.X === offset) return;
    // x的值0 - 290
    if (offset < 0 || offset > 290) {
      throw new Error('蛇撞墙了');
    }
    // 移动蛇身体
    this.handleMoveBody();
    this.head.style.left = offset + 'px';
  }
  // 设置到蛇头的Y轴坐标的方法
  set Y(offset: number) {
    // if (this.Y === offset) return;
    // x的值0 - 290
    if (offset < 0 || offset > 290) {
      throw new Error('蛇撞墙了');
    }
    // 移动蛇身体
    this.handleMoveBody();
    this.head.style.top = offset + 'px';
  }

  // 设置蛇运动的方向
  // setDirection(direction: string): void {
  //   this.direction = direction;
  // }

  // 还是需要定义一个私有属性direction才行。这样写的好处
  get direction(): string {
    return this.#direction;
  }
  set direction(direction: string) {
    console.log(direction);
    this.#direction = direction;
  }

  // 判断是否可以设置运动方法
  handleCheckDirection(key: string) {
    // ArrowUp
    // ArrowRight
    // ArrowDown
    // ArrowLeft
    if (
      (this.direction === 'ArrowUp' && key === 'ArrowDown') ||
      (this.direction === 'ArrowDown' && key === 'ArrowUp')
    )
      return false;
    if (
      (this.direction === 'ArrowLeft' && key === 'ArrowRight') ||
      (this.direction === 'ArrowRight' && key === 'ArrowLeft')
    )
      return false;

    return true;
  }

  // 处理蛇移动位置和移动的大小
  handleMoveLocationSize(X: number, Y: number, offset: number) {
    // 根据按键的方向，修改蛇为位置
    switch (this.direction) {
      case 'ArrowUp':
        Y -= offset;
        break;
      case 'ArrowRight':
        X += offset;
        break;
      case 'ArrowDown':
        Y += offset;
        break;
      case 'ArrowLeft':
        X -= offset;
        break;
    }
    return { X, Y };
  }

  // 蛇增加身体的方法
  handleAddBody() {
    this.element.insertAdjacentHTML(
      'beforeend',
      "<div class='snake-body'></div>"
    );
  }

  // 移动身体的方法
  handleMoveBody() {
    for (let i = this.bodyies.length - 1; i > 0; i--) {
      let X = (this.bodyies[i - 1] as HTMLElement).offsetLeft;
      let Y = (this.bodyies[i - 1] as HTMLElement).offsetTop;
      (this.bodyies[i] as HTMLElement).style.left = X + 'px';
      (this.bodyies[i] as HTMLElement).style.top = Y + 'px';
    }
  }
}

export default Snake;
